package com.distribution.system.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.distribution.common.core.domain.AjaxResult;
import com.distribution.common.utils.StringUtils;
import com.distribution.system.domain.bo.RefreshOrderBO;
import com.distribution.system.domain.entity.CmccDaOrder;
import com.distribution.system.domain.entity.CmccDaProduct;
import com.distribution.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;

import static com.distribution.common.core.domain.AjaxResult.error;
import static com.distribution.common.core.domain.AjaxResult.success;

/**
 * 接收回调
 * @author walle
 * @date 2021/3/31 15:16
 **/
@Slf4j
@RequestMapping(value = "/receive")
@RestController
public class ReceiveController {
    private static final Logger sjkOrderNotifyLog = LoggerFactory.getLogger("sjkOrderNotifyLog");
    private static final Logger qkOrderNotifyLog = LoggerFactory.getLogger("qkOrderNotifyLog");
    private static final Logger ylbOrderNotifyLog = LoggerFactory.getLogger("ylbOrderNotifyLog");
    private static final Logger mzOrderNotifyLog = LoggerFactory.getLogger("mzOrderNotifyLog");
    private static final Logger ayOrderNotifyLog = LoggerFactory.getLogger("ayOrderNotifyLog");
    @Resource
    FuluUploadPeopleService fuluUploadPeopleService;
    @Resource
    FuluUploadPlanService fuluUploadPlanService;
    @Resource
    CmccDaOrderService cmccDaOrderService;
    @Resource
    CmccDaProductService cmccDaProductService;
    @Resource
    CmccDaUpChannelInfoService cmccDaUpChannelInfoService;


    /**
     * 接收结清申请结果, 更新推送记录表
     *
     * @param json json
     * @return string code 0/90001
     */
    @PostMapping(value = "/orderMessage")
    public AjaxResult orderMessage(@RequestBody JSONObject json) {
        log.info("接收【三剑客】订单返回结果:{}",json);
        sjkOrderNotifyLog.info("接收【三剑客】订单返回结果:{}",json);
        // 状态 ：0=进行中，1=已激活 4=失败 6=已首充（宽带已竣工） 10=已开户 11=已发货
        try {
            RefreshOrderBO refreshOrderBO = new RefreshOrderBO();
            String productStatus = "-1";
            String status = "2";
            Integer state = json.getInteger("state");// 状态 ：0=进行中，1=已激活 4=失败 6=已完成/首充（该状态说明平台已结佣金） 10=已开户 11=已发货
            if (state == 6){
                status = "3";
                productStatus = "6";
            }else {
                if (state == 4){
                    status = "-1";
                }
                if (state == 1){
                    productStatus = "1";
                }
                if (state == 10){
                    productStatus = "10";
                }
                if (state == 11){
                    productStatus = "11";
                }
            }
            refreshOrderBO.setProductStatus(productStatus);// 卡状态
            refreshOrderBO.setStatus(status);
            refreshOrderBO.setStatusMsg(json.getString("info"));// 返回描述 （如：销户，首充不满足条件等）
            refreshOrderBO.setProductStatus(state == 6 ? "6" : state.toString());// 渠道方状态
            refreshOrderBO.setScMoney(String.valueOf(json.getBigDecimal("lgtsId").multiply(new BigDecimal("100"))));// 首充金额（元），部分订单可能会返回空
            refreshOrderBO.setPhone(json.getString("number"));// 订购号码
            refreshOrderBO.setCreateTime(json.getString("createtime")); // 更新时间
            refreshOrderBO.setLimitTime(json.getString("actime")); // 激活时间（部分订单可能会返回空）
            refreshOrderBO.setChannelOrderNo(json.getString("orderId"));// 渠道方订单号
            refreshOrderBO.setLogisticsInfo(json.getString("wlCompany") + "-" + json.getString("wlOrderid"));// 物流信息
            CmccDaOrder cmccDaOrder = cmccDaOrderService.lambdaQuery().eq(CmccDaOrder::getChannelOrderNo, refreshOrderBO.getChannelOrderNo()).one();
            cmccDaOrderService.refreshOrderStatusByRefreshOrderBO(cmccDaOrder, refreshOrderBO);
        } catch (Exception e) {
            log.error("根据【三剑客】推送消息更新订单失败", e);
            ylbOrderNotifyLog.error("根据【三剑客】推送消息更新订单失败", e);
        }
        return success();
    }

    @PostMapping(value = "/qkOrderMessage")
    public JSONObject qkOrderMessage(@RequestBody JSONObject json) {
        log.info("接收【秋葵】订单返回结果:{}",json);
        qkOrderNotifyLog.info("接收【秋葵】订单返回结果:{}",json);
        JSONObject returnJson = new JSONObject();
        // 号卡状态 【0 失败 1下单成功 2 已发货 3 已撤单 4 已签收 5 已激活 6 已首充】宽带状态【 0 失败 1下单成功 3 已撤单 6 已竣工】
        try {
            RefreshOrderBO refreshOrderBO = new RefreshOrderBO();
            String status = "2";
            String productStatus = "-1";
            String orderStatus = json.getString("orderStatus");// 号卡状态 【0 失败 1下单成功 2 已发货 3 已撤单 4 已签收 5 已激活 6 已首充】宽带状态【 0 失败 1下单成功 3 已撤单 6 已竣工】
            if ("0".equals(orderStatus)) {
                status = "-1";
                productStatus = "-2";
            } else if ("2".equals(orderStatus)){
                productStatus = "11";
            } else if ("5".equals(orderStatus)){
                productStatus = "1";
            } else if ("6".equals(orderStatus)) {
                status = "3";
                productStatus = "6";
            }
            refreshOrderBO.setStatus(status);
            refreshOrderBO.setProductStatus(productStatus);
            refreshOrderBO.setChannelOrderNo(json.getString("orderSn"));// 渠道方订单号
            refreshOrderBO.setStatusMsg(json.getString("description"));// 状态描述
            // 这里首冲金额单位是元，需要转换为分
            String rechargeAmount = json.getString("rechargeAmount");// 充值金额
            String s = StringUtils.isEmpty(rechargeAmount) ? "0" : (new BigDecimal(rechargeAmount).multiply(new BigDecimal(100))).toString();
            refreshOrderBO.setScMoney(s);
            // 首冲金额不为空且>0则已首充
            refreshOrderBO.setProductStatus(Integer.parseInt(s) > 0 ? "6" : "-1");
            refreshOrderBO.setPhone(json.getString("selectPhone"));// 订购号码
            refreshOrderBO.setCreateTime(json.getString("orderTime"));// 订购时间
            refreshOrderBO.setLimitTime(json.getString("activeTime"));// 激活时间
            String logisticsInfo = StringUtils.isNotBlank(json.getString("logisticsName")) && StringUtils.isNotBlank(json.getString("logisticsNum")) ?
                    json.getString("logisticsName") + "-" + json.getString("logisticsNum") : "无";
            refreshOrderBO.setLogisticsInfo(logisticsInfo);// 物流名称-物流单号
            CmccDaOrder cmccDaOrder = cmccDaOrderService.lambdaQuery().eq(CmccDaOrder::getChannelOrderNo, refreshOrderBO.getChannelOrderNo()).one();
            cmccDaOrderService.refreshOrderStatusByRefreshOrderBO(cmccDaOrder, refreshOrderBO);
            returnJson.put("code","200");
            returnJson.put("success",true);
            returnJson.put("msg","ok");
        } catch (Exception e) {
            log.error("根据【秋葵】推送消息更新订单失败", e);
            qkOrderNotifyLog.error("根据【秋葵】推送消息更新订单失败", e);
            returnJson.put("code","400");
            returnJson.put("success",false);
            returnJson.put("msg","no");
        }
        return returnJson;
    }

    @PostMapping(value = "/ylbOrderMessage")
    public AjaxResult ylbOrderMessage(@RequestBody JSONObject json) {
        log.info("接收【168】订单返回结果:{}",json);
        ylbOrderNotifyLog.info("接收【168】订单返回结果:{}",json);
        // 状态 ：0=进行中，1=已激活 4=失败 6=已首充（宽带已竣工） 10=已开户 11=已发货
        try {
            RefreshOrderBO refreshOrderBO = new RefreshOrderBO();
            refreshOrderBO.setChannelOrderNo(json.getString("orderId"));// 渠道方订单号
            refreshOrderBO.setPhone(json.getString("number"));// 订购号码
            String productStatus = "-1";
            String status = "2";
            Integer state = json.getInteger("state");// 状态 ：0=进行中，1=已激活 4=失败 6=已完成/首充（该状态说明平台已结佣金） 10=已开户 11=已发货
            if (state == 6) {
                status = "3";
                productStatus = "6";
            } else {
                if (state == 4) {
                    status = "-1";
                }
                if (state == 1){
                    productStatus = "1";
                }
                if (state == 10){
                    productStatus = "10";
                }
                if (state == 11){
                    productStatus = "11";
                }
            }
            refreshOrderBO.setProductStatus(productStatus);// 卡状态
            refreshOrderBO.setStatus(status);
            String acTime = json.getString("actime");// 激活时间（部分订单可能会返回空）
            String scTime = json.getString("sctime");// 首充时间（部分订单可能会返回空）
            // 查订单
            CmccDaOrder cmccDaOrder = cmccDaOrderService.getOne(new LambdaQueryWrapper<CmccDaOrder>().eq(CmccDaOrder::getChannelOrderNo, refreshOrderBO.getChannelOrderNo()), false);
            if (cmccDaOrder == null){
                log.error("根据渠道方订单编号【{}】查询订单不存在或存在多条记录", refreshOrderBO.getChannelOrderNo());
                ylbOrderNotifyLog.error("根据渠道方订单编号【{}】查询订单不存在或存在多条记录", refreshOrderBO.getChannelOrderNo());
                // 查不到商品的话就按号卡处理
                refreshOrderBO.setLimitTime(scTime); // 激活时间（部分订单可能会返回空）
            }else {
                // 查商品
                CmccDaProduct cmccDaProduct = cmccDaProductService.getOne(new LambdaQueryWrapper<CmccDaProduct>().eq(CmccDaProduct::getProductCode, cmccDaOrder.getProductCode()), false);
                refreshOrderBO.setLimitTime("1".equals(cmccDaProduct.getBroadbandFlag()) ? acTime : scTime);
            }
            refreshOrderBO.setStatusMsg(json.getString("info"));// 返回描述 （如：销户，首充不满足条件等）
            // 这里首冲金额单位是元，需要转换为分
            try {
                String doMoney = json.getString("scmoney");// 首充金额（元），部分订单可能会返回空
                String s = StringUtils.isEmpty(doMoney) ? "0" : (new BigDecimal(doMoney).multiply(new BigDecimal(100))).toString();
                refreshOrderBO.setScMoney(s);
            } catch (Exception e) {
                log.error("首冲金额由元转换为分时出错，原因{}", e.getMessage());
                ylbOrderNotifyLog.error("首冲金额由元转换为分时出错，原因{}", e.getMessage());
            }
            refreshOrderBO.setLogisticsInfo(json.getString("wlCompany") + "-" + json.getString("wlOrderid"));// 物流信息
            refreshOrderBO.setCreateTime(json.getString("createtime")); // 更新时间
            cmccDaOrderService.refreshOrderStatusByRefreshOrderBO(cmccDaOrder, refreshOrderBO);
        } catch (Exception e) {
            log.error("根据【168】推送消息更新订单失败", e);
            ylbOrderNotifyLog.error("根据【168】推送消息更新订单失败", e);
            return error();
        }
        return success();
    }

    @PostMapping(value = "/mzOrderMessage")
    public AjaxResult mzOrderMessage(@RequestBody JSONObject json) {
        log.info("接收【麦众】订单返回结果:{}",json);
        mzOrderNotifyLog.info("接收【麦众】订单返回结果:{}",json);
        // 状态 ：0=进行中，1=已激活 4=失败 6=已首充（宽带已竣工） 10=已开户 11=已发货
        try {
            RefreshOrderBO refreshOrderBO = new RefreshOrderBO();
            refreshOrderBO.setOrderId(json.getString("upOrderCode"));// 己方订单号
            refreshOrderBO.setChannelOrderNo(json.getString("orderCode"));// 渠道方订单号
            String status = "2";
            if ("0".equals(json.getString("state"))){// 订单状态 1.下单成功 0.订单失败
                status = "-1";
            }
            if ("1".equals(json.getString("isActive"))){// 竣工状态 为1表示已竣工
                status = "3";
            }
            refreshOrderBO.setStatus(status);
            refreshOrderBO.setLimitTime(json.getString("activeTime"));// 竣工时间
            refreshOrderBO.setFailureReason(json.getString("errMsg"));// 失败原因
            CmccDaOrder cmccDaOrder = cmccDaOrderService.lambdaQuery().eq(CmccDaOrder::getOrderId, refreshOrderBO.getOrderId()).one();
            cmccDaOrderService.refreshOrderStatusByRefreshOrderBO(cmccDaOrder, refreshOrderBO);
        } catch (Exception e) {
            log.error("根据【麦众】推送消息更新订单失败", e);
            mzOrderNotifyLog.error("根据【麦众】推送消息更新订单失败", e);
            return error();
        }
        return success();
    }

    @PostMapping(value = "/ayOrderMessage")
    public JSONObject ayOrderMessage(@RequestBody JSONObject json) {
        log.info("接收【奥亚】订单返回结果:{}", json);
        ayOrderNotifyLog.info("接收【奥亚】订单返回结果:{}",json);
        JSONObject returnJson = new JSONObject();
        try {
            JSONObject body = json.getJSONObject("body");
            RefreshOrderBO refreshOrderBO = new RefreshOrderBO();
            refreshOrderBO.setOrderId(body.getString("openid"));// 下单接口传入的订单号
            refreshOrderBO.setPhone(body.getString("simMobile"));// 选购的号码
            String productStatus = "-1";
            String orderStatus = "2";
            Integer state = body.getInteger("state");
            switch (state) {
                case 1:// 成功结算
                    orderStatus = "3";
                    break;
                case 2:// 失败
                    orderStatus = "-1";
                    break;
                default:
                    orderStatus = "2";
                    break;
            }
            refreshOrderBO.setStatus(orderStatus);
            Integer uniState = body.getInteger("uniState");
            switch (uniState) {
                case 0:// 下单
                    productStatus = "-1";
                    break;
                case 1:// 激活
                    productStatus = "1";
                    break;
                case 6:// 首充
                    productStatus = "6";
                    break;
                default:
                    productStatus = "-1";
                    break;
            }
            refreshOrderBO.setProductStatus(productStatus);
            refreshOrderBO.setScMoney(String.valueOf(body.getInteger("lgstId")));// 首冲金额（元）
            CmccDaOrder cmccDaOrder = cmccDaOrderService.lambdaQuery().eq(CmccDaOrder::getOrderId, refreshOrderBO.getOrderId()).one();
            cmccDaOrderService.refreshOrderStatusByRefreshOrderBO(cmccDaOrder, refreshOrderBO);
        } catch (Exception e) {
            log.error("根据【奥亚】推送消息更新订单失败", e);
            ayOrderNotifyLog.error("根据【奥亚】推送消息更新订单失败", e);
            returnJson.put("code",1);
            return returnJson;
        }
        returnJson.put("code",0);
        return returnJson;
    }









    /**
     * 接收结清申请结果, 更新推送记录表
     *
     * @param params json
     * @return string code 0/90001
     */
    @PostMapping(value = "/fuluMessage")
    public String fuluMessage(@RequestParam Map<String, String> params) {
        log.info("接收福穗返回结果:{}",params);
        String s = JSONObject.toJSONString(params);
        JSONObject json = JSONObject.parseObject(s);
        try {
            String msgMethod = json.getString("msgMethod");
            if ("people_status_callback".equals(msgMethod)) {
                fuluUploadPeopleService.fuluMessage(json);
            }
            if ("plan_status_callback".equals(msgMethod)) {
                fuluUploadPlanService.fuluMessage(json);
            }
        } catch (Exception e) {
            log.error("根据【福穗】推送消息更新订单失败", e);
        }
        return "success";
    }
}
